<template>
  <e-container :loading="loading">
    <e-title title="Bank Info" />
    <a-divider />
    <div class="form">
      <a-form ref="formRef" :model="apiData" layout="vertical" :rules="rules">
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item name="signedCompany">
              <template #label>
                <a-space>
                  <span>Invoice Entity</span>
                  <a-tooltip v-if="hasAdvanceBalance">
                    <template #title>
                      Can't change invoice entity at this time, because the client has a balance.
                    </template>
                    <e-icon type="tips" style="cursor: help" />
                  </a-tooltip>
                </a-space>
              </template>
              <a-select
                v-model:value="apiData.signedCompany"
                :disabled="hasAdvanceBalance"
                show-search
                option-filter-prop="label"
                :get-popup-container="triggerNode => triggerNode.parentNode"
                @change="companyChange"
              >
                <a-select-option
                  v-for="item in companies"
                  :key="item.id"
                  :label="item.branchNameCN + item.branchNameEN"
                >
                  <a-space>
                    {{ item.branchNameCN }}
                    <span v-if="item.branchNameCN !== item.branchNameEN" style="color: #bfbfbf">
                      {{ item.branchNameEN }}
                    </span>
                  </a-space>
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Invoice Address" name="pdfCompanyName">
              <a-select
                v-model:value="apiData.pdfCompanyName"
                show-search
                option-filter-prop="label"
                option-label-prop="label"
                :get-popup-container="triggerNode => triggerNode.parentNode"
                @change="pdfCompanyChange"
              >
                <a-select-option v-for="item in state.pdfCompanyList" :key="item.id" :label="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Contact Number" name="ecContact">
              <a-input v-model:value="apiData.ecContact" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Fax" name="ecFax">
              <a-input v-model:value="apiData.ecFax" disabled />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Address" name="ecAddress">
              <a-textarea v-model:value="apiData.ecAddress" disabled style="min-height: 80px" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Invoice Bank Account" name="accountName">
              <a-select
                v-model:value="apiData.accountName"
                show-search
                option-filter-prop="label"
                option-label-prop="label"
                :get-popup-container="triggerNode => triggerNode.parentNode"
                @change="accountNameChange"
              >
                <a-select-option v-for="item in state.accountList" :key="item.id" :label="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <span style="color: #818d9f; font-size: 14px">Invoice Details</span>
            <div class="information" v-html="apiData.accountInformation"></div>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Invoice Template" name="templateId">
              <a-select
                v-model:value="apiData.templateId"
                show-search
                option-filter-prop="label"
                option-label-prop="label"
                :get-popup-container="triggerNode => triggerNode.parentNode"
              >
                <a-select-option v-for="item in state.templateList" :key="item.id" :label="item.name">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!--          <a-col v-if="apiData.templateId === 31 || apiData.templateId === 35" :span="12">
            <a-form-item label=" ">
              <div
                style="
                  border: 1px solid #e1e6f0;
                  padding: 0 12px;
                  height: 32px;
                  line-height: 32px;
                  cursor: pointer;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  white-space: nowrap;
                "
                @click="apiData.isIdenticalArea = !apiData.isIdenticalArea">
                <a-checkbox v-model:checked="apiData.isIdenticalArea" />
                <span
                  v-if="apiData.templateId === 31"
                  style="margin-left: 6px"
                  title='Include "VAT 27%", Because the client and the invoice entity in the same place.'>
                  Include "VAT 27%", Because the client and the invoice entity in the same place.
                </span>
                <span
                  v-if="apiData.templateId === 35"
                  style="margin-left: 6px"
                  title='Include "GST 7%", Because the client and the invoice entity in the same place.'>
                  Include "GST 7%", Because the client and the invoice entity in the same place.
                </span>
              </div>
            </a-form-item>
          </a-col>-->
        </a-row>
      </a-form>
    </div>
    <a-divider />
    <div class="buttons">
      <a-space size="middle">
        <a-button @click="handleCancel">Cancel</a-button>
        <a-button v-permission="'FinancialInformation:BackInfo:Edit'" type="primary" @click="handleSave">Save</a-button>
      </a-space>
    </div>
  </e-container>
</template>

<script setup>
import { ref, reactive, computed, inject, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import EContainer from '@/components/EContainer.vue'
import ETitle from '@/components/ETitle.vue'
import EIcon from '@/components/EIcon.vue'
import { CONFIRM_BACK_TO_DETAIL, SAVED_SUCCESSFULLY } from '@/constants/message'
import financial from '@/api/client/financial.js'

const route = useRoute()
const router = useRouter()
const store = useStore()
const emits = defineEmits(['updated'])
const loading = ref(true)
const { id } = route.params
const gutter = [120, 16]
const { Modal, message } = inject('Feedback')
const rules = {
  signedCompany: [
    {
      required: true,
      // whitespace: true,
      message: 'Please Select Invoice Entity.'
    }
  ],
  pdfCompanyName: [
    {
      required: true,
      // whitespace: true,
      message: 'Please Select Invoice Address.'
    }
  ],
  accountName: [
    {
      required: true,
      // whitespace: true,
      message: 'Please Select Invoice Bank Account.'
    }
  ]
}
const apiData = reactive({
  signedCompany: undefined,
  pdfCompanyName: undefined,
  ecContact: '',
  ecFax: '',
  ecAddress: '',
  accountName: undefined,
  accountInformation: '',
  templateId: undefined,
  isIdenticalArea: false,
  taxRate: 0
})
const state = reactive({
  // 发票地址名称
  pdfCompanyList: [],
  // 收款银行账号
  accountList: [],
  // Invoice模板
  templateList: []
})
const formRef = ref()
const companies = ref([])
const eciCompanies = ref()
const accountNames = ref()
const accountId = ref()
const hasAdvanceBalance = ref(true)
/**
 * 获取可用的公司选项
 */
const getSignedCompany = () => {
  financial.getSignedCompany(id).then(({ data }) => {
    companies.value = data
    if (Array.isArray(companies.value) && !companies.value.find(item => item.id === apiData.signedCompany)) {
      // 如果可选公司中没有当前的数据，则将当前的数据设为空
      apiData.signedCompany = undefined
    }
  })
}
/**
 * 保存
 */
const handleSave = () => {
  formRef.value.validate().then(() => {
    if (apiData.templateId !== 31 && apiData.templateId !== 35) {
      apiData.taxRate = 0
    } else {
      if (apiData.templateId === 31 && apiData.isIdenticalArea) {
        apiData.taxRate = 0.27
      } else if (apiData.templateId === 35 && apiData.isIdenticalArea) {
        apiData.taxRate = 0.07
      } else {
        apiData.taxRate = 0
      }
    }
    financial
      .updateClientFinanceTrade({
        id,
        signedCompany: apiData.signedCompany,
        collectionsAccount: apiData.accountName,
        invoiceECAddress: apiData.pdfCompanyName,
        invoiceTemplet: apiData.templateId,
        isIdenticalArea: apiData.isIdenticalArea,
        taxRate: apiData.taxRate
      })
      .then(res => {
        if (res.code === 2000) {
          message.success(SAVED_SUCCESSFULLY)
          router.push({ name: 'Financial Information' })
          emits('updated')
        }
      })
  })
}
/**
 * 取消
 */
const handleCancel = () => {
  Modal.confirm({
    content: CONFIRM_BACK_TO_DETAIL,
    okButtonProps: { danger: true },
    onOk: () => {
      router.push({ name: 'Financial Information' })
      emits('updated')
    }
  })
}
/**
 * 获取模板
 */
const getTemplate = () => {
  financial.getFinancialTemplate().then(res => {
    if (res.code === 2000) {
      state.templateList = res.data
    }
  })
}
/**
 * 获取发票地址名称
 * @param id
 */
const getEciAddress = id => {
  return financial
    .getEciAddress({
      companyID: id
    })
    .then(res => {
      if (res.code === 2000) {
        eciCompanies.value = res.data
        state.pdfCompanyList = []
        eciCompanies.value.forEach(item => {
          const obj = {}
          obj.id = item.id
          obj.text = item.ecName
          state.pdfCompanyList.push(obj)
        })
      }
    })
}
/**
 * 获取收款银行账号
 * @param id
 */
const getCollectionAccount = id => {
  return financial
    .getCollectionAccount({
      companyID: id
    })
    .then(res => {
      if (res.code === 2000) {
        accountNames.value = res.data
        state.accountList = []
        accountNames.value.forEach(item => {
          if (item.status === 0 || item.id === accountId.value) {
            const obj = {}
            obj.id = item.id
            obj.text = item.accountName
            state.accountList.push(obj)
          }
        })
      }
    })
}
/**
 * 修改收款公司
 * @param val
 */
const companyChange = val => {
  apiData.pdfCompanyName = undefined
  apiData.ecContact = ''
  apiData.ecFax = ''
  apiData.ecAddress = ''
  apiData.accountName = undefined
  apiData.accountInformation = ''
  getEciAddress(val)
  getCollectionAccount(val)
}
/**
 * 修改发票地址名称
 * @param val
 */
const pdfCompanyChange = val => {
  const res = eciCompanies.value.find(item => item.id === val)
  apiData.ecAddress = res.ecAddress || ''
  apiData.ecFax = res.ecFax || ''
  apiData.ecContact = res.ecContact || ''
}
/**
 * 修改收款银行账号
 * @param val
 */
const accountNameChange = val => {
  const res = accountNames.value.find(item => item.id === val)
  apiData.accountInformation = res.accountInformation
}
/**
 * 初始化
 */
onMounted(() => {
  financial
    .getFinancialBank(id)
    .then(res => {
      if (res.code === 2000) {
        accountId.value = res.data.collectionsAccount || undefined
        apiData.signedCompany = res.data.signedCompany || undefined
        apiData.pdfCompanyName = res.data.invoiceECAddress || undefined
        apiData.accountName = res.data.collectionsAccount || undefined
        apiData.ecContact = res.data.pdfCompanyTel
        apiData.ecFax = res.data.pdfCompanyFax
        apiData.ecAddress = res.data.pdfCompanyAddress
        apiData.accountInformation = res.data.bankAccountDetail
        apiData.templateId = res.data.invoiceTemplate || undefined
        apiData.isIdenticalArea = res.data.isIdenticalArea
        apiData.taxRate = res.data.taxRate
        hasAdvanceBalance.value = res.data.hasAdvanceBalance
        getEciAddress(apiData.signedCompany)
        getCollectionAccount(apiData.signedCompany)
        getTemplate()
        getSignedCompany()
      }
    })
    .finally(() => {
      loading.value = false
    })
})
</script>

<style scoped lang="less">
.form {
  padding: 0 228px;
}
.buttons {
  text-align: center;
}
.information {
  width: 100%;
  min-height: 80px;
  border: 1px solid #e1e6f0;
  background-color: #f2f2f2;
  border-radius: 2px;
  padding-top: 7px;
  padding-left: 10px;
  color: #262626;
  margin-top: 6px;
  margin-bottom: 16px;
}
:deep(.ant-divider) {
  border-top: 1px solid #dcdee7 !important;
}
:deep(.ant-input),
:deep(.ant-select),
:deep(.ant-input-number),
:deep(.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
  border-color: @border-color !important;
}
.ant-input[disabled] {
  color: @text-black;
}
</style>
<route lang="yaml">
name: Bank Info
path: '/client/:id/financial-information/bank-info'
meta:
  title: Bank Info
  permission: FinancialInformation
</route>
